import 'package:flutter/foundation.dart';
import 'package:meco/common/models/recommended_video_model.dart';
import 'package:meco/common/data/services/database_service.dart';

/// 视频删除观察者接口
abstract class VideoDeleteObserver {
  /// 当视频被删除时调用
  void onVideoDeleted(int videoId);
}

class RecommendedVideoRepository {
  // 观察者列表
  static final List<VideoDeleteObserver> _observers = [];

  // 添加观察者
  static void addObserver(VideoDeleteObserver observer) {
    if (!_observers.contains(observer)) {
      _observers.add(observer);
    }
  }

  // 移除观察者
  static void removeObserver(VideoDeleteObserver observer) {
    _observers.remove(observer);
  }

  // 通知所有观察者视频已被删除
  static void notifyVideoDeleted(int videoId) {
    for (var observer in _observers) {
      observer.onVideoDeleted(videoId);
    }
  }

  final DatabaseService _databaseService = DatabaseService();
  final String _tableName = 'recommended_videos';

  // 获取所有推荐视频
  Future<List<RecommendedVideo>> getAllRecommendedVideos() async {
    final db = await _databaseService.database;
    try {
      final List<Map<String, dynamic>> maps = await db.query(_tableName);
      return maps.map((map) => RecommendedVideo.fromJson(map)).toList();
    } catch (e) {
      debugPrint('获取推荐视频列表失败: $e');
      return [];
    }
  }

  // 获取单个推荐视频
  Future<RecommendedVideo?> getRecommendedVideoById(int id) async {
    final db = await _databaseService.database;

    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'id = ?',
        whereArgs: [id],
      );

      if (maps.isEmpty) {
        return null;
      }

      return RecommendedVideo.fromJson(maps.first);
    } catch (e) {
      print('获取单个推荐视频失败: $e');
      return null;
    }
  }

  // 创建推荐视频
  Future<int> createRecommendedVideo(RecommendedVideo video) async {
    final db = await _databaseService.database;
    final now = DateTime.now().millisecondsSinceEpoch;

    final videoMap = video.toJson();
    videoMap['created_at'] = now;
    videoMap['updated_at'] = now;

    try {
      return await db.insert(_tableName, videoMap);
    } catch (e) {
      print('创建推荐视频失败: $e');
      return -1;
    }
  }

  // 更新推荐视频
  Future<bool> updateRecommendedVideo(RecommendedVideo video) async {
    if (video.id == null) {
      return false;
    }

    final db = await _databaseService.database;
    final videoMap = video.toJson();
    videoMap['updated_at'] = DateTime.now().millisecondsSinceEpoch;

    try {
      final result = await db.update(
        _tableName,
        videoMap,
        where: 'id = ?',
        whereArgs: [video.id],
      );
      return result > 0;
    } catch (e) {
      print('更新推荐视频失败: $e');
      return false;
    }
  }

  // 删除推荐视频
  Future<bool> deleteRecommendedVideo(int id) async {
    final db = await _databaseService.database;

    try {
      final result = await db.delete(
        _tableName,
        where: 'id = ?',
        whereArgs: [id],
      );
      return result > 0;
    } catch (e) {
      print('删除推荐视频失败: $e');
      return false;
    }
  }

  // 增加视频点赞数
  Future<bool> incrementLikeCount(int videoId) async {
    final db = await _databaseService.database;

    try {
      await db.rawUpdate(
        'UPDATE $_tableName SET like_count = like_count + 1, updated_at = ? WHERE id = ?',
        [DateTime.now().millisecondsSinceEpoch, videoId],
      );
      return true;
    } catch (e) {
      print('增加点赞数失败: $e');
      return false;
    }
  }

  // 减少视频点赞数
  Future<bool> decrementLikeCount(int videoId) async {
    final db = await _databaseService.database;

    try {
      await db.rawUpdate(
        'UPDATE $_tableName SET like_count = MAX(0, like_count - 1), updated_at = ? WHERE id = ?',
        [DateTime.now().millisecondsSinceEpoch, videoId],
      );
      return true;
    } catch (e) {
      print('减少点赞数失败: $e');
      return false;
    }
  }

  // 增加视频收藏数
  Future<bool> incrementFavoriteCount(int videoId) async {
    final db = await _databaseService.database;

    try {
      await db.rawUpdate(
        'UPDATE $_tableName SET favorite_count = favorite_count + 1, updated_at = ? WHERE id = ?',
        [DateTime.now().millisecondsSinceEpoch, videoId],
      );
      return true;
    } catch (e) {
      print('增加收藏数失败: $e');
      return false;
    }
  }

  // 减少视频收藏数
  Future<bool> decrementFavoriteCount(int videoId) async {
    final db = await _databaseService.database;

    try {
      await db.rawUpdate(
        'UPDATE $_tableName SET favorite_count = MAX(0, favorite_count - 1), updated_at = ? WHERE id = ?',
        [DateTime.now().millisecondsSinceEpoch, videoId],
      );
      return true;
    } catch (e) {
      print('减少收藏数失败: $e');
      return false;
    }
  }

  // 删除视频
  Future<bool> deleteVideo(int videoId) async {
    final db = await _databaseService.database;
    try {
      // 从数据库中删除视频
      final result = await db.delete(
        _tableName,
        where: 'id = ?',
        whereArgs: [videoId],
      );

      // 如果删除成功，通知所有观察者
      if (result > 0) {
        notifyVideoDeleted(videoId);
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('删除视频失败: $e');
      return false;
    }
  }
}
